package com.tms.app.tms.ui;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.alibaba.sdk.android.ams.common.util.StringUtil;
import com.tms.app.tms.R;
import com.tms.app.tms.app.Constant;
import com.tms.app.tms.bean.Fee;
import com.tms.app.tms.bean.FeeName;
import com.tms.app.tms.bean.ImgBean;
import com.tms.app.tms.bean.response.BaseResponse;
import com.tms.app.tms.bean.response.FeeNameRes;
import com.tms.app.tms.ui.base.presenter.ComPresenter;
import com.tms.app.tms.ui.base.ui.AbsPhotoPickActivity;
import com.tms.app.tms.ui.taskinfo.TaskInfoActivity;
import com.tms.app.tms.utils.SharePreferenceUtil;
import com.tms.app.tms.widget.CommonDialog;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.xutils.http.RequestParams;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2017/10/28 0028.
 */

public class FeeAddAc extends AbsPhotoPickActivity {
    @BindView(R.id.text_fee_type)
    TextView textFeeType;
    @BindView(R.id.text_fee_price)
    EditText textFeePrice;
    @BindView(R.id.text_mark)
    EditText textMark;
    @BindView(R.id.spinner)
    Spinner spinner;
    @BindView(R.id.text_order_no)
    TextView textOrderNo;
    @BindView(R.id.button_send)
    Button buttonSend;
    private int waybillExecId;
    ComPresenter presenter = new ComPresenter();
    private Fee fee;
//    private String[] feeNames;
//    private String[] feeNameids;
    private String WaybillNo = "";
    private int planIdShowType = -1;
    private CommonDialog commonDialog;
    private  String dialogTitle="确定要保存费用吗";
    private ArrayAdapter<String> spinnerAdapter;
    private List<String > feeList=new ArrayList<>();
    private List<String > feeIdList=new ArrayList<>();
    private List<FeeName > feeNameList=new ArrayList<>();
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);

        setToolBarTitle("费用申请", -1, -1);
        waybillExecId = getIntent().getIntExtra("waybillExecId", -1);
        WaybillNo = getIntent().getStringExtra("waybillNo");
        planIdShowType = getIntent().getIntExtra("planIdShowType", -1);
        String feeJson = getIntent().getStringExtra("fee");
        if (feeJson != null && feeJson.length() > 1) {
            fee = gson.fromJson(feeJson, Fee.class);
            bindToView();
        }
        initView();

    }

    private void initView() {
//        feeNames = getResources().getStringArray(R.array.fee_name);
//        feeNameids = getResources().getStringArray(R.array.fee_name_id);
        if (WaybillNo == null)
            WaybillNo = "";
        textOrderNo.setText("运单号：" + WaybillNo);
        switch (planIdShowType) {//派车单状态 0 待执行，1执行中，2 司机已完成3，确认已完成
            case 11:
            case 1:
            case 2:
            case 12:
                buttonSend.setVisibility(View.VISIBLE);
                break;
            case 3:
            case 13:
                buttonSend.setVisibility(View.GONE);
                break;

        }
       spinnerAdapter=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, feeList);
        spinner .setAdapter(spinnerAdapter);
        presenter.getFeeList();
    }

    @Override
    public void initLayout() {
        setContentView(R.layout.ac_layout_fee_add);
    }

    @OnClick({R.id.text_fee_type, R.id.button_send})
    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.text_fee_type:
                break;
            case R.id.button_send:
                commonDialog= CommonDialog.getInstance(this, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        saveFee();
                        commonDialog.close();
                    }
                },dialogTitle);
                commonDialog.show();

                break;
        }
    }

    private void bindToView() {
        if (fee == null)
            return;
        textFeeType.setTag(fee.getFeeTypeName());
        textFeePrice.setText(fee.getFeeValue() + "");
        textMark.setText(fee.getRemark());
        for (int i = 0; i < fee.getImgList().size(); i++) {
            imgServerList.put(imgViewList.get(i), fee.getImgList().get(i).getImgSrc());
        }
        buttonSend.setText("变更保存");
        loadPickPhoto();
    }

    @Override
    public void delSerImg(int index) {
        if (fee == null)
            return;
//        RequestParams params = new RequestParams(Constant.FeeDel);
//        params.addBodyParameter("token", token);
//        params.addBodyParameter("attachId", fee.getImgList().get(index) + "");
//        presenter.getObjectFromServer(params, 1);
    }

    public void saveFee() {
        String feePrice = textFeePrice.getText().toString();
        String remark = textMark.getText().toString();
        final RequestParams params = new RequestParams(Constant.ExFeeSave);
        params.addBodyParameter("token", token);
        params.addBodyParameter("waybillExecId", waybillExecId + "");
        if (fee!=null&&fee.getFeeId()>0){
            params.addBodyParameter("feeId", fee.getFeeId()+"");
            dialogTitle="确定要修改费用吗?";
        }
        if (StringUtil.isEmpty(feePrice)){
                showMsg("请输入费用金额");
                return ;
        }
        params.addBodyParameter("amount", feePrice);
        params.addBodyParameter("remark", remark);
        params.setMultipart(true);
        List<String> list = new ArrayList<>();
        for (View view : imgSelectList.keySet()) {
            if (imgSelectList.get(view) != null && !imgSelectList.get(view).equals("-1")) {
                list.add(imgSelectList.get(view));
            }
        }
        for (int i = 0; i < list.size(); i++) {
            params.addBodyParameter("files", new File(list.get(i)));
        }
        for (int i = 0; i < feeList.size(); i++) {
            if (feeList.get(i).equals(spinner.getSelectedItem().toString())) {
                params.addBodyParameter("feeNameId", feeIdList.get(i));
            }
        }
        StringBuffer sb = new StringBuffer();
        for (View view : imgServerList.keySet()) {
            if (imgServerList.get(view)!=null&&!imgServerList.get(view).equals("-1")){
                sb.append(imgServerList.get(view)).append(",");
            }
        }
        String imgs = "";
        if (sb.length() > 2) {
            imgs = sb.subSequence(0, sb.length() - 1).toString();
        }
        params.addBodyParameter("imgs",imgs);
        presenter.saveFee(params);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void checkSave(String json) {
        BaseResponse baseResponse = gson.fromJson(json, BaseResponse.class);
        if (baseResponse.getCode() == 200) {
            showMsg("异常费用保存成功");
            setResult(Constant.fineshFeeAdd);
            finish();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void checkSave(FeeNameRes feeNameRes) {
        int selsetTy=0;
        if (feeNameRes.getCode() == 200) {
            feeNameList=feeNameRes.getData();
           feeList.clear();
            feeIdList.clear();
            for (int i = 0; i < feeNameList.size(); i++) {
                FeeName feeName=feeNameList.get(i);
                feeList.add(feeName.getFee_name());
                feeIdList.add(feeName.getId()+"");
                try {
                    if (feeName.getFee_name().equals(fee.getFeeTypeName())){
                        selsetTy=i;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            spinnerAdapter.notifyDataSetChanged();
            spinner.setSelection(selsetTy);
        }
    }
}
